﻿using SmartSapce.ServiceLocation;
using SmartSpace.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SmartSpace.WebApp._console.core
{
    public partial class role_detail : System.Web.UI.Page
    {
        public Guid RoleId { get; private set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            RoleId = SmartSpace.Web.RequestUtility.GetGuid(this.Request, "id");

            if (!IsPostBack)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                Role role = service.GetRole(RoleId);

                _ctlEditCode.Text = role.Code;
                this._ctlEditCaption.Text = role.Caption;

                ICoreSearcher searcher = ServiceLocator.Get<ICoreSearcher>();
                ListResult<RolePrivilegeDetail> detailList = searcher.FindPrivilege(RoleId);
                this._ctlList.DataSource = detailList.Data;
                this._ctlList.DataBind();

                ListResult<Role> parentRoles = service.GetParentRoles(RoleId);
                this._ctlListParentRoles.DataSource = parentRoles.Data;
                this._ctlListParentRoles.DataBind();
            }
        }

        protected void _ctlBtnUnRelate_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();
            Role role = service.GetRole(RoleId);

            foreach (RepeaterItem item in _ctlListParentRoles.Items)
            {
                CheckBox checkBox = (CheckBox)item.FindControl("_ctlCheck");
                if (checkBox != null && checkBox.Checked)
                {
                    HiddenField hiddenField = (HiddenField)item.FindControl("_ctlTag");
                    Guid parentId = new Guid(hiddenField.Value);
                    service.UnRelateRole(RoleId, parentId);
                }
            }

            Response.Redirect(string.Format("./role-detail.aspx?id={0}", RoleId));
        }
    }
}